<?php

namespace djepo\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use djepo\UserBundle\Entity\Notification;
use djepo\UserBundle\Form\NotificationType;
use Symfony\Component\HttpFoundation\Response;

/**
 * Notification controller.
 *
 * @Route("/api/notification")
 */
class NotificationRestController extends Controller
{
    /**
     * Lists all Notification entities.
     *
     * @Route("/", name="notification")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('djepoUserBundle:Notification')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Count all unread notifications.
     *
     * @Route("/count")
     * @Method("POST")
     * @Template()
     */
    public function countAction()
    {
        $em = $this->getDoctrine()->getManager();
        $serializer = $this->get('serializer'); 

        $userId = $this->get('request')->query->get('user');
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);

        $qb = $em->createQueryBuilder();
        $qb->select('n');
        $qb->from('djepoUserBundle:Notification','n');
        $qb->where('n.user = :user');
        $qb->setParameter('user',$user);
        $qb->andWhere('n.view = :view');
        $qb->setParameter('view',false);
        $notifications =  array();
        foreach ($qb->getQuery()->getResult() as $notification) {
            $action = $em->getRepository('djepoUserBundle:ProductAction')->find($notification->getObjectId());

            $arrNot['username'] = $action->getUser()->getFirstName()." ".$action->getUser()->getLastName();
            $arrNot['userpicture'] = $action->getUser()->getPicture();
            $arrNot['object'] = $notification->getObject();
            $arrNot['objectId'] = $notification->getObjectId();
            $arrNot['view'] = $notification->getView();
            $arrNot['date'] = $notification->getDate();
            array_push($notifications, $arrNot);
        }
        

        return new Response($serializer->serialize($notifications , 'json'));
    }

   
}
